<?php
/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link http://www.workerman.net/
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */

/**
 * 用于检测业务代码死循环或者长时间阻塞等问题
 * 如果发现业务卡死，可以将下面declare打开（去掉//注释），并执行php start.php reload
 * 然后观察一段时间workerman.log看是否有process_timeout异常
 */
//declare(ticks=1);
use common\helpers\ShowFunction;
use common\helpers\ShowJson;
use common\models\workerman\WebSocketBase;

/**
 * 主逻辑
 * 主要是处理 onConnect onMessage onClose 三个方法
 * onConnect 和 onClose 如果不需要可以不用实现并删除
 */
class Events
{
    public static $fileName = "workerman_events_mocktest";
    public static $project = "mocktest";
    
    /**
     * 当客户端连接时触发
     * 如果业务不需此回调可以删除onConnect
     * 
     * @param int $client_id 连接id
     */
    public static function onConnect($client_id) 
    {
        ShowFunction::writeLog(self::$fileName, date("Y-m-d H:i:s") . "||" . $client_id . " is connect");
        $client_uid = ShowFunction::realIp();
        $wsBaseObj = new WebSocketBase();
        $wsBaseObj->bindClientId($client_id, $client_uid, self::$project);
        $wsBaseObj->sendMessageToClient($client_id, array("type" => "text", "msg" => "连接成功"));
    }
    
   /**
    * 当客户端发来消息时触发
    * @param int $client_id     连接id
    * @param string $message    接收到的消息内容
    * @return
    */
   public static function onMessage($client_id, $message) 
   {
       ShowFunction::writeLog(self::$fileName, date("Y-m-d H:i:s") . "||" . $client_id . "--" . $message);
       if (empty($message)) {
           return false;
       }
       $content = ShowJson::decode($message, true);
       if (empty($content) || empty($content['type'])) {
           return false;
       }
       ShowFunction::writeLog(self::$fileName, date("Y-m-d H:i:s") . "||" . $client_id . "--" . $content['type']);
       
       $wsBaseObj = new WebSocketBase();
       $res = $wsBaseObj->sendMessageToClient($client_id, $content, self::$project);
       if ($res == false) {
           ShowFunction::writeLog(self::$fileName, date("Y-m-d H:i:s") . "||" . $client_id . "--" . $wsBaseObj->getError());
       }
       return true;
   }
   
   /**
    * 当用户断开连接时触发
    * @param int $client_id 连接id
    */
   public static function onClose($client_id) 
   {
       ShowFunction::writeLog(self::$fileName, date("Y-m-d H:i:s") . "||" . $client_id . " is closed");
       $wsBaseObj = new WebSocketBase();
       $wsBaseObj->sendMessageToClient($client_id, array("type" => "text", "msg" => "连接已断开"), self::$project);
       $wsBaseObj->closeClient($client_id, self::$project);
   }
}
